package cn.monkey.transport.netty.server.codec.protocol.tcp.http.ws;

import cn.monkey.transport.netty.server.codec.protocol.tcp.http.HttpServerProtocolPredicate;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.util.ReferenceCountUtil;

public interface WebsocketServerProtocolPredicate extends HttpServerProtocolPredicate {

    WebsocketServerProtocolPredicate INSTANCE = new WebsocketServerProtocolPredicate() {
    };


    @Override
    default boolean test0(SocketChannel channel, ByteBuf data) {
        if (!HttpServerProtocolPredicate.super.test0(channel, data)) {
            return false;
        }
        ByteBuf byteBuf = Unpooled.copiedBuffer(data);
        try {
            String s = new String(byteBuf.array());
            String[] split = s.split("\n");

            for (String line : split) {
                String[] pair = line.split(": ");
                if (pair.length != 2) {
                    continue;
                }
                if (HttpHeaderNames.UPGRADE.contentEqualsIgnoreCase(pair[0])) {
                    String upgradeVal = pair[1].trim();
                    return "WEBSOCKET".equalsIgnoreCase(upgradeVal);
                }
            }
            return false;
        } finally {
            ReferenceCountUtil.release(byteBuf);
        }
    }
}
